package com.xyp.a_demo;

/**
 * --- 加油，努力 ---
 *
 * @Author XYP
 * @Date 2024/8/6
 * @Desc 从想做到能做
 */
class Printer {
    public static int count = 1;
    public static int p1Orp2 = 1;
    static Object lock = new Object();
}
class Print1 implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (Printer.lock) {
                if (Printer.count > 10) {
                    break;
                } else {
                    if (Printer.p1Orp2 == 2) {
                        try {
                            Printer.lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        System.out.println("print1正在执行...");
                        Printer.p1Orp2 = 2;
                        Printer.count++;
                        Printer.lock.notifyAll();
                    }
                }
            }
        }
    }

}

class Print2 implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (Printer.lock) {
                if (Printer.count > 10) {
                    break;
                } else {
                    if (Printer.p1Orp2 == 1) {
                        try {
                            Printer.lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        System.out.println("print2正在执行...");
                        Printer.p1Orp2 = 1;
                        Printer.lock.notifyAll();
                    }
                }
            }
        }
    }

}

public class Demo4 {
    public static void main(String[] args) {

        new Thread(new Print1()).start();
        new Thread(new Print2()).start();

    }
}
